import { proxy, reqHeader, formatDate, stringify, ossuploadurl,banPNG} from '../../utils/util.js';
import LoginStore from '../login/store.js';
import PhotoselectStore from '../photoselect/store.js';
import {
  encode
} from '../../libs/querystring/index.js';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    userData:{},
    infoObj: {},
    choosePop:false,
    chooseList:[],
    disabled:true,
    startDate:"1900-01-01",
    newDate:formatDate(new Date(),'-')
  },
  changeInfo: function (key,value){
    let obj={};
    let infoObj = this.data.infoObj;
    infoObj[key] = value;
    obj.infoObj = infoObj;
    if (this.data.disabled){
      obj.disabled = false
    } else if (key === 'nickName' && !value.replace(/(^\s*)|(\s*$)/g, "")){
      obj.disabled = true;
    }
    this.setData(obj);
  },
  inputHandler:function(e){
    let key = e.currentTarget.dataset.key;
    let value = e.detail.value;
    this.changeInfo(key,value);
  },
  hideModal:function(){
    this.setData({
      choosePop: false
    })
  },
  showChoosePop:function(){
    this.setData({
      choosePop:true,
      chooseList:[{
        type:'sex',
        key:'1',
        name:'男'
      },{
        type: 'sex',
        key: '2',
        name: '女'
      }]
    })
  },
  chooseClick:function(e){
    let pages = getCurrentPages();
    let lastPage = pages[pages.length - 2];
    lastPage.setData({
      freshMark: true
    })
    let me = this;
    if (e.detail.type == 'sex'){
      this.changeInfo('sex', e.detail.key);
    }
    else if (e.detail.type == 'cover'){
      if (e.detail.key == "fromAlbum"){
        wx.chooseImage({
          count: 1,
          sizeType: ['original'],
          sourceType: ['album', 'camera'],
          success: function (res) {
            var path = res.tempFilePaths;
            if (!banPNG(path)) {
              return;
            }
            //上传
            wx.showLoading({
              title: '上传中...',
            })
            me.uploadFun(path);
          }
        })

      } else if (e.detail.key == "fromWorks"){
        let getUrl = () => {
          var urlParamstr = encode({
            access_token: LoginStore.userInfo.access_token,
            resourceType: '0,2',
            imgsize:"p1,p2,p3",
            startTime:'',
            type:'json' 
          });
          return `${proxy}/community/v2/user/myphoto?` + urlParamstr
        }
        PhotoselectStore.setAjaxUrl(getUrl(''));
        wx.navigateTo({
          url: `/pages/photoselect/photoselect?editInfo=true`
        });
      }
    }
    else if (e.detail.type == 'avatar' && e.detail.key == "fromAlbum"){
      wx.chooseImage({
        count: 1,
        sizeType: ['original'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          let path = res.tempFilePaths;
          if (!banPNG(path)) {
            return;
          }
          //上传
         
          wx.uploadFile({
            url: `${proxy}/community/upload_avatar.html`,
            filePath: path[0],
            name: "loadPhoto",
            header: Object.assign({
              "Content-Type": "multipart/form-data",
            }, reqHeader),
            formData:{
              "access_token": LoginStore.userInfo.access_token
            },
            success: function (res) {
              if (res.statusCode == 200){
                res = JSON.parse(res.data);
                me.setData({
                  avatarUrl: res.avatar.a1
                },()=>{
                  me.changeStorage(function (loginData) {
                    loginData.userInfo.avatar = res.avatar;
                  })
                });
              }
            },
            fail: function (err) {
              console.log(err)
            },
          })
        }
      })
    }
  },
  uploadFun: function (names) {
    let me = this;
    wx.request({
      url: `${proxy}/community/v2/upload/ossInfo`,
      data: {
        access_token: LoginStore.userInfo.access_token,
        originalNames: JSON.stringify(names),
        uploadType: 'photo'
      },
      header: reqHeader,
      success: function (res) {
        if (res.statusCode != 200) {
          return;
        }
        res = res.data;
        if (res.status == 200) {
          res.data.forEach((_item, _index) => {
            me.uploadImage({
              item: _item,
              index: _index,
              ossInfo: res.ossInfo,
              filePath: _item.fileName,
              ossId: _item.ossId
            })

          });
        } else {
          console.log(res.message);
        }
      }
    })
  },
  uploadImage(params) {
    let me = this;

    wx.getImageInfo({
      src: params.filePath,
      success: function (imgInfo) {
        let _index = params.index;
        var ossInfo = params.ossInfo;
        
        wx.uploadFile({
          url: ossInfo.host,
          filePath: params.filePath,
          name: 'file', //必须填file
          formData: {
            'key': params.ossId,
            'policy': ossInfo.policy,
            'OSSAccessKeyId': ossInfo.accessid,
            'signature': ossInfo.signature,
            'success_action_status': '200',
          },
          success: function (res) {
            if (res.statusCode != 200) {
              console.log(new Error('上传错误:' + JSON.stringify(res)))
              return;
            }
            console.log('上传图片成功', res);
            
            wx.request({
              url: `${proxy}/community/settings/cover2`,
              method: 'POST',
              data: {
                coverUrl: params.item.url,
                access_token: LoginStore.userInfo.access_token
              },
              header: Object.assign({
                'content-type': 'application/x-www-form-urlencoded'
              }, reqHeader),
              success: function (_res) {
                _res = _res.data;
                if (_res.status == 200){
                  wx.hideLoading();
                  me.setData({
                    coverUrl: _res.url.p3
                  });
                }else{
                  console.log('error');
                }
                
              }
            })
          },
          fail: function (err) {
            console.log(err)
          },
        })

      }
    })


  },
  bindDateChange:function(e){
    this.changeInfo('birthday', e.detail.value);
  },
  changeCoverUrl:function(){
    this.setData({
      choosePop: true,
      chooseList: [{
        type: 'cover',
        key: 'title',
        name: '更换个人主页封面'
      }, {
        type: 'cover',
        key: 'fromAlbum',
        name: '从手机相册选择'
      }, {
        type: 'cover',
        key: 'fromWorks',
        name: '从已有作品选择'
      }]
    })
  },
  changeAvatarUrl: function () {
    this.setData({
      choosePop: true,
      chooseList: [{
        type: 'avatar',
        key: 'title',
        name: '更换个人头像'
      }, {
        type: 'avatar',
        key: 'fromAlbum',
        name: '从手机相册选择'
      }]
    })
  },
  changeStorage: function (action){
    let loginData = wx.getStorageSync('loginData');
    action(loginData);
    wx.setStorage({
      key: 'loginData',
      data: loginData
    })
  },
  saveInfo:function(){
    let me = this;
    if(this.data.disabled){
      return;
    }
    let infoObj = {...this.data.infoObj};
    if (infoObj.birthday){
      infoObj.birthday = new Date(infoObj.birthday).getTime();
    }

    wx.request({
      url: `${proxy}/user/v2/settings/save`,
      data: {
        jsonData: stringify(infoObj),
        access_token: LoginStore.userInfo.access_token
      },
      method: 'POST',
      header: Object.assign({
        'content-type': 'application/x-www-form-urlencoded'
      }, reqHeader),
      success: function (res) {
        if (res.statusCode != 200) {
          return;
        }
        res = res.data;
        if (res.status == 200){
          wx.showToast({
            title:'成功'
          });
          me.changeStorage(function (loginData) {
            loginData.userInfo.nickName = infoObj.nickName;
          });
          setTimeout(()=>{
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            prevPage.setData({
              freshMark: true
            }, function () {
              wx.navigateBack({
                delta: 1
              })
            });
          },1000);
        }else{
          console.log(res.message)
        }
      }

    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let me = this;
    wx.request({
      url: `${proxy}/user/v2/settings/info`,
      data:{
        access_token: LoginStore.userInfo.access_token
      },
      header: reqHeader,
      success:function(res){
        if (res.statusCode != 200){
          return;
        }
        res = res.data;
        if (res.status == 200){
          let infoObj={
            nickName: res.data.user.nickName,
            about: res.data.userProperty.about,
            coutry: res.data.userProperty.coutry,
            province: res.data.userProperty.province,
            city: res.data.userProperty.city
          };
          if (res.data.userProperty.sex && res.data.userProperty.sex == 2){
            infoObj.sex = '2';
          } else if (res.data.userProperty.sex && res.data.userProperty.sex == 1){
            infoObj.sex = '1';
          }
          let startDate = "1900-01-01";
          if (res.data.userProperty.birthday == undefined){
            infoObj.birthday = "";
          }else{
            let birthYear = new Date(res.data.userProperty.birthday).getFullYear();
            let birthday = formatDate(new Date(res.data.userProperty.birthday), '-');
            
            if (birthYear < 1900){
              startDate = birthday;
            }
            infoObj.birthday = birthday;
          }
          me.setData({
            userData:res.data,
            infoObj: infoObj,
            coverUrl: res.data.user.coverUrl.baseUrl + '!p3',
            avatarUrl: res.data.user.avatar.baseUrl + '!a1',
            startDate: startDate
          })
        }else{
          console.log(res.message);
        }
      }

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.freshMark == undefined || !this.data.freshMark) {
      return;
    }
    this.onLoad();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      freshMark: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }
})